package me.zxk.qwert_poetry.service;

import me.zxk.qwert_poetry.dao.User;
import me.zxk.qwert_poetry.dao.UserRepository;
import me.zxk.qwert_poetry.dto.SimpleUserDTO;
import me.zxk.qwert_poetry.util.ApiException;
import me.zxk.qwert_poetry.util.JwtUtil;
import me.zxk.qwert_poetry.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    private final int ERR_USER_NOT_FOUND = 1000; // 用户不存在
    private final int ERR_NICKNAME_INVALID = 1001; // 昵称格式错误
    private final int ERR_EMAIL_INVALID = 1002; // 邮箱格式错误
    private final int ERR_EMAIL_EXIST = 1003; // 邮箱已存在
    private final int ERR_PASSWORD_EMPTY = 1004; // 密码为空
    private final int ERR_PHONE_INVALID = 1005; // 手机号格式错误

    private boolean validateUserInfo(User u) {
        // 昵称 3~20 字符
        if (StringUtil.isNullOrEmpty(u.getNickname()))
            throw new ApiException("昵称未填写", ERR_NICKNAME_INVALID);
        if (u.getNickname().length() < 3 || u.getNickname().length() > 20)
            throw new ApiException("昵称长度应为 3~20 字符", ERR_NICKNAME_INVALID);
        // 邮箱格式
        if (StringUtil.isNullOrEmpty(u.getEmail()))
            throw new ApiException("邮箱未填写", ERR_EMAIL_INVALID);
        if (!StringUtil.isEmail(u.getEmail()))
            throw new ApiException("邮箱格式不正确", ERR_EMAIL_INVALID);
        // 密码
        if (StringUtil.isNullOrEmpty(u.getPasswordHash()))
            throw new ApiException("密码未填写", ERR_PASSWORD_EMPTY);
        // 手机号
        if (!StringUtil.isNullOrEmpty(u.getPhoneNumber()) && !StringUtil.isChinaPhoneNumber(u.getPhoneNumber()))
            throw new ApiException("手机号格式不正确", ERR_PHONE_INVALID);
        return true;
    }

    /**
     * @param u
     * @return 登录成功返回 JWT Token 字符串，失败 NULL
     */
    @Override
    public String loginById(User u) {
        User userInDb = userRepository.findById(u.getId())
                .orElseThrow(() -> new ApiException("用户不存在", ERR_USER_NOT_FOUND));

        if (userInDb.getPasswordHash().equals(u.getPasswordHash()))
            return JwtUtil.getJwtToken(userInDb);
        else
            return null;
    }

    @Override
    public String loginByEmail(User u) {
        User userInDb = userRepository.findByEmail(u.getEmail())
                .orElseThrow(() -> new ApiException("用户不存在", ERR_USER_NOT_FOUND));

        if (userInDb.getPasswordHash().equals(u.getPasswordHash()))
            return JwtUtil.getJwtToken(userInDb);
        else
            throw new ApiException("密码不正确", 1005);
    }

    @Override
    public User register(User u) {
        validateUserInfo(u);
        if (userRepository.findByEmail(u.getEmail()).isPresent())
            throw new ApiException("该邮箱已存在", ERR_EMAIL_EXIST);
        return userRepository.save(u);
    }

    @Override
    public User updateProfile(User u) {
        User userInDb = userRepository.findById(u.getId())
                .orElseThrow(() -> new ApiException("用户不存在", ERR_USER_NOT_FOUND));
        validateUserInfo(u);
        userInDb.setNickname(u.getNickname());
        userInDb.setEmail(u.getEmail());
        userInDb.setPhoneNumber(u.getPhoneNumber());
        return userRepository.save(userInDb);
    }

    @Override
    public User getUserById(int id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new ApiException("用户不存在", ERR_USER_NOT_FOUND));
    }

    @Override
    public void deleteUserById(int id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new ApiException("用户不存在", ERR_USER_NOT_FOUND));
        userRepository.deleteById(id);
    }

    @Override
    public User getUserByEmail(String email) {
        return userRepository.findByEmail(email)
                .orElseThrow(() -> new ApiException("用户不存在", ERR_USER_NOT_FOUND));
    }
}
